import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios'
import router from '@/router'
import Cookies from 'js-cookie'

const baseURL = import.meta.env.VITE_REQUEST_BASEURL

const instance = axios.create({
  baseURL,
  timeout: 15 * 1000,
  headers: {
    // Environment: '',
  }
})

interface ResponseData<D> {
  data: D
  result_code: string
  result_msg: string
}

const client = <T = unknown>(
  url: string,
  data?: object,
  conf: AxiosRequestConfig = {}
): Promise<T> => {
  const token = Cookies.get('token')
  const requestConf: AxiosRequestConfig = {
    method: 'GET',
    url,
    headers: {
      token
    },
    ...conf
  }

  const requestType = 'pc'

  const t = new Date().valueOf()

  if (requestConf.method?.toUpperCase() === 'GET') {
    requestConf.params = { ...data, requestType, t }
    requestConf.headers = {
      ...requestConf.headers,
      'Content-Type': '*/*'
    }
  } else if (requestConf.method?.toUpperCase() === 'POST') {
    requestConf.params = { requestType, t }
    requestConf.data = data
  }

  return instance(requestConf).then(
    // 拦截正常响应做一些处理
    ({ status: responseCode, data: responseData, config }: AxiosResponse<ResponseData<T>>) => {
      // 响应200
      if (responseCode === 200) {
        if (config.responseType === 'arraybuffer') {
          const blob = new Blob([responseData as unknown as BlobPart], {
            type: 'application/pdf;chartset=UTF-8'
          })
          const fileURL = URL.createObjectURL(blob)
          window.open(fileURL)
        } else {
          const { data, result_code: businessCode } = responseData

          switch (businessCode) {
            case '200':
            case '100300':
              return Promise.resolve(data)
            case '403':
              // logOut()
              iframeLogOut(true)
              break
            default: {
              return Promise.reject(responseData)
            }
          }
        }
      }
      // 响应非200
      return Promise.reject(responseData)
    },
    // 捕获错误响应做一些处理
    (err: Error) => {
      return Promise.reject(err)
    }
  )
}

export function logOut() {
  if (import.meta.env.DEV) {
    router.replace('/login')
  } else {
    // window.location.href = `${origin}/${import.meta.env.BASE_URL}`

    const { origin } = window.location
    window.location.href = `${origin}/logout.do`
  }
}

export function iframeLogOut(timeOut?: boolean) {
  if (window.top === window.self) {
    logOut()
  } else {
    window.top?.postMessage(
      {
        type: 'logOut',
        timeOut
      },
      '*'
    )
  }
}

export { instance, client }
